/**
* 图片上传（单文件版）
*/
<template>
	<div class="w100">
		<el-upload v-if="!disabled" action="" :before-upload="beforeUpload" :show-file-list="false"
			accept=".jpg,.jpeg,.gif,.png,.webp" style="display: flex;">
			<vp-btn :loading="loading" type="primary" class="mr-20">
				<slot v-if="$slots.header" name="header" />
				<div v-else>
					<vp-label zh="上传" en="Upload" />
					<SvgIcon name="ele-Upload" class="el-icon--right"></SvgIcon>
				</div>
			</vp-btn>
		</el-upload>
		<el-upload v-if="previewList.length > 0" action="" list-type="picture-card" v-model:file-list="previewList"
			class="mt8" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :disabled="disabled">
		</el-upload>

		<el-image-viewer v-if="dialogVisible" :url-list="[dialogImageUrl]" hide-on-click-modal teleported
			@close="dialogVisible = false" />
	</div>
</template>
<script setup lang="ts" name="vpImageSigleUpload">
import { ref, computed, nextTick } from 'vue';
import request from '/@/utils/request';

// 模型值改为单个对象而非数组
const modelValue = defineModel({ type: Object, default: null });
const emits = defineEmits(['change']);

const props = defineProps({
	disabled: {
		type: Boolean,
		default: false,
	},
});

const loading = ref(false);

const dialogImageUrl = ref('');
const dialogImageName = ref('');
const dialogVisible = ref(false);

// 上传文件之前的方法 - 改为处理单个文件
const beforeUpload = (file: any) => {
	if (file) {
		let submitData = new FormData();
		submitData.append('file', file);
		loading.value = true;
		request.post(`/file/upload`, submitData, { headers: { 'content-type': 'multipart/form-data' } }).then(res => {
			loading.value = false;
			// 只取第一个文件作为结果
			if (res.data && res.data.length) {
				modelValue.value = res.data[0];

				console.log(modelValue.value,"modelValue.value")
				console.log(res.data[0],"res.data[0]")
				nextTick(() => {
					emits("change", modelValue.value);
				});
			}
		});
	}
	return false;
};

// 预览列表改为数组形式，但只包含一个元素
const previewList = computed(() => {
	if (!modelValue.value) return [];

	return [{
		id: modelValue.value.id,
		name: modelValue.value.yswjm + '.' + modelValue.value.hzm,
		url: `${import.meta.env.VITE_API_URL}/file/stream/${modelValue.value.id}`,
	}]
});


// 预览图片
const handlePictureCardPreview = (uploadFile: any) => {
	dialogImageUrl.value = uploadFile.url!;
	dialogImageName.value = uploadFile.name;
	dialogVisible.value = true;

}

// 删除图片
const handleRemove = () => {
	modelValue.value = null;
	emits("change", modelValue.value);
}

</script>
<style scoped>
:deep(.el-upload--picture-card) {
	display: none;
}
</style>
